var designClass = "design_class", hideClass = "hide_class", browseClass = "browse_class", addClass = "add_class", editClass = "edit_class";
var upWindow = window.parent.frames["zwIframe"];
if (!upWindow) {
    upWindow = window.parent.frames["componentDiv"].frames["zwIframe"];
}
//关闭自定义扩张控件弹出窗口
function fy_dialog_close() {
    window.parent.$(".layui-layer-iframe").parent().find(".layui-layer-close").trigger("click");
}

function getUpFieldsByFieldval(name) {
    return upWindow.$("[fieldval*='displayName:\"" + name + "\"']");
}

function getUpFieldValue(field) {
    var fieldVal = field.attr("fieldVal");
    var editTag = field.hasClass(editClass);
    var browseTag = field.hasClass(browseClass);
    var addTag = field.hasClass(addClass);
    if (fieldVal != null && typeof (fieldVal) != 'undefined') {
        fieldVal = eval("(" + fieldVal + ")");
    } else {
        return null;
    }
    var obj = new Object();
    obj.displayName = fieldVal.displayName;
    obj.name = fieldVal.name;
    var tag = true;
    switch (fieldVal.inputType) {
        case "text":
        case "textarea":

            if (editTag) {
                obj.value = field.find("#" + fieldVal.name).val();
            } else if (browseTag) {
                obj.value = fieldVal.value;
            } else if (addTag) {
                obj.value = field.find("#" + fieldVal.name).val();
            }
            break;
        case "checkbox":
            if (editTag) {
                obj.value = field.find("#" + fieldVal.name).val();
            } else if (browseTag) {
                obj.value = field.find("#" + fieldVal.name).val();
            }
            break;
        case "radio":
            if (editTag) {
                obj.value = field.find(":radio:checked").attr("val4cal");
            } else if (browseTag) {
                obj.value = field.find(":radio:checked").attr("val4cal");
            }
            break;
        case "select":
            if (editTag) {
                obj.value = field.find("#" + fieldVal.name + " option:selected")
                        .attr("val4cal");
            } else if (browseTag) {
                obj.value = field.find("#" + fieldVal.name).attr("val4cal");
            }
            break;
        case "date":
            if (editTag) {
                obj.value = field.find("#" + fieldVal.name).val();
                if (obj.value != "") {
                    obj.value = obj.value + " 00:00";
                }
            } else if (browseTag) {
                obj.value = fieldVal.value;
            }
            break;
        case "datetime":
            if (editTag) {
                obj.value = field.find("#" + fieldVal.name).val();
            } else if (browseTag) {
                obj.value = fieldVal.value;
            }
            break;
        case "flowdealoption":
            if (editTag) {
                obj.value = fieldVal.value;
            } else if (browseTag) {
                obj.value = fieldVal.value;
            } else if (addTag) {
                obj.value = fieldVal.value;
            }
            break;
        case "lable":
            if (editTag) {
                obj.value = fieldVal.value;
            } else if (browseTag) {
                obj.value = fieldVal.value;
            }
            break;
        case "relationform":
            if (editTag) {
                obj.value = fieldVal.value;
            } else if (browseTag) {
                obj.value = fieldVal.value;
            }
            break;
        case "relation":
            if (editTag || browseTag) {
                obj.value = fieldVal.value;
            }
            break;
        case "project":
            if (editTag) {
                obj.value = field.find("#" + fieldVal.name).val();
            } else if (browseTag) {
                obj.value = fieldVal.value;
            }
            break;
        case "member":
        case "multimember":
        case "account":
        case "multiaccount":
        case "department":
        case "multidepartment":
        case "post":
        case "multipost":
        case "level":
        case "multilevel":
            if (editTag) {
                obj.value = field.find("#" + fieldVal.name + "_txt").val();
                obj.id = field.find("#" + fieldVal.name).val().split('|')[1];
            } else if (browseTag) {
                obj.value = field.find("#" + fieldVal.name).text();
            }
            break;
        case "attachment":
        case "image":
        case "document":
            if (editTag || browseTag) {
                var attNames = "";
                var tempField = field.find("#" + fieldVal.name);
                var tempFileId = "";
                if (tempField[0].tagName.toLowerCase() == "input") {
                    tempFileId = tempField.val();
                } else if (tempField[0].tagName.toLowerCase() == "span") {
                    tempFileId = tempField[0].innerHTML;
                }
                var atts = upWindow.getAttBySubreference(tempFileId);
                for (var j = 0; j < atts.length; j++) {
                    attNames += atts[j].filename + ",";
                }
                if (attNames != "") {
                    attNames = attNames.substr(0, attNames.length - 1);
                }
                obj.value = attNames;
            }
            break;
        case "outwrite":
            if (editTag || browseTag) {
                obj.value = fieldVal.value;
            }
            break;
        case "externalwrite-ahead":
            if (editTag || browseTag) {
                obj.value = fieldVal.value;
            }
            break;
        case "exchangetask":
            if (editTag || browseTag) {
                obj.value = fieldVal.value;
            }
            break;
        case "querytask":
            if (editTag || browseTag) {
                obj.value = fieldVal.value;
            }
            break;
        default:
            tag = false;
    }
    if (obj.value != undefined) {
        obj.value = obj.value.replace("\r\n", ";");
        obj.value = obj.value.replace("\n", ";");
    }
    return obj;
}

function setUpFieldValue2(field, value, displayValue, index) {

    try {

        var fieldVal = field.attr("fieldVal");
        var editTag = field.hasClass(editClass);
        var addTag = field.hasClass(addClass);
        value = (value);
        displayValue = displayValue ? (displayValue) : displayValue;
        if (fieldVal != null && typeof (fieldVal) != 'undefined') {
            fieldVal = eval("(" + fieldVal + ")");
        } else {
            return null;
        }
        var tag = true;
        switch (fieldVal.inputType) {
            case "text":
            case "textarea":
                if (editTag) {
                    var inField = field.find("#" + fieldVal.name);
                    inField.val(value);
                    inField.trigger("blur");
                } else if (addTag) {
                    var inField = field.find("#" + fieldVal.name);
                    inField.val(value);
                    inField.trigger("blur");
                }
                break;
            case "checkbox":
                if (editTag) {
                    field.find("#" + fieldVal.name).attr("checked", true);
                    field.find("#" + fieldVal.name).trigger("click");
                }
                break;
            case "radio":
                if (editTag) {
                    field.find(":radio").eq(index).attr("checked", true);
                    field.find(":radio").eq(index).trigger("click");
                }
                break;
            case "select":
                if (editTag) {
                    var options = field.find("#" + fieldVal.name + " option");
                    for (var k = 0; k < options.length; k++) {
                        if (options.eq(k).text() == value)
                            options.eq(k).attr("selected", true);
                    }
                    field.find("#" + fieldVal.name).trigger("change");
                }
                break;
            case "date":
                if (editTag) {
                    field.find("#" + fieldVal.name).val(value);
                    field.find("#" + fieldVal.name).trigger("blur");
                }
                break;
            case "datetime":
                if (editTag) {
                    field.find("#" + fieldVal.name).val(value);
                    field.find("#" + fieldVal.name).trigger("blur");
                }
                break;
            case "member":
            case "multimember":
            case "account":
            case "multiaccount":
            case "department":
            case "multidepartment":
            case "post":
            case "multipost":
            case "level":
            case "multilevel":
                if (editTag) {
//				alert(editTag);
                    field.find("#" + fieldVal.name).val(value);
                }
                break;
        }
    } catch (e) {
        // TODO: handle exception
    }
}
//添加或者删除行
function addOrDelRepeat(name, newLength) {
    var fields = getUpFieldsByFieldval(name);
    var oldLength = fields.length;
    var tbody = getUpFieldsByFieldval(name).eq(0).parent();
    while (!tbody.is("tbody")) {
        tbody = tbody.parent();
    }
    for (var i = 0, length = Math.abs(newLength - oldLength); i < length; i++) {
        if (newLength > oldLength) {
            upWindow.fy_addEmpty(tbody.children().last());
        } else {
            upWindow.fy_delCurrentRepeat(tbody.children().last());
        }
    }
    upWindow.fy_setReadonly();
}

function $(name) {
    return document.getElementsByName(name);
}

var inputMap = {
    "失效供应商名称": "invalidName",
    "失效供应商编码": "invalidCode",
    "备注": "remark",
    "失效地点": "address",
    "失效日期": "date"
};

var notAllowBlank = {
    invalidName: "失效供应商名称",
    invalidCode: "失效供应商编码",
    date: "失效日期",
    address: "失效地点"
}

function corpValueChange(node) {
    var selectNodes = $('corpSelect');
    for (var i = 0; i < selectNodes.length; i++) {
        selectNodes[i].value = node.value;
    }
    var inputs = document.getElementsByTagName("input");
    for (var i = 0; i < inputs.length; i++) {
        if (inputs[i].id != 'ok_button')
            inputs[i].value = "";
    }
}

function createOption(msg, key) {
    var op = document.createElement("option");
    op.value = key;
    op.text = msg;
    return op;
}

/**
 * 全角转半角，小写转大写
 * 
 * @param {}
 *            field
 */
function replaceIllegalCharacter(field) {
    var charlist = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    charlist += "abcdefghijklmnopqrstuvwxyz";
    charlist += "0123456789";
    charlist += " `~!@#$%^&*()_+-={}|[]\:\\\";'<>?,./";// 半角空格

    var providerName = field.value;
    var result = "";
    for (var i = 0; i < providerName.length; i++) {
        var c1 = providerName.charAt(i);
        var c2 = providerName.charCodeAt(i);
        if ("　" == c1) {
            result += " ";
        } else if ("，" == c1) {
            result += ",";
        } else if ("。" == c1) {
            result += ".";
        } else {
            if (charlist.indexOf(String.fromCharCode(c2 - 65248)) > -1) {
                result += String.fromCharCode(c2 - 65248);
            } else {
                result += c1;
            }
        }
    }
    field.value = result.toUpperCase();
}

function supplierCodeValueChange(field, supplierName) {
    setButtonDisabled(true);
    replaceIllegalCharacter(field);

    var supplierCode = field.value;
    if (supplierCode.replace(/ /g, "") == "") {
        var inputs = getParentTR(field).parentNode
                .getElementsByTagName("input");
        for (var i = 0; i < inputs.length; i++) {
            if (inputs[i].name == supplierName) {
                inputs[i].value = "";
                break;
            }
        }
        setButtonDisabled(false);
    } else {
        var pk_corp = $("corpSelect")[0].value.replace("key_", "");

        var inputs = getParentTR(field).parentNode
                .getElementsByTagName("input");
        for (var i = 0; i < inputs.length; i++) {
            if (inputs[i].name == supplierName) {
                inputs[i].value = "";
                break;
            }
        }
        _ajax(
                "../oa2uapController.do?method=financeProviderOperate&operate=1&code="
                + supplierCode + "&pk_corp=" + pk_corp + "&isNew="
                + (field.name == "newSupplierCode"), function (data) {
            var inputs = getParentTR(field).parentNode
                    .getElementsByTagName("input");
            for (var i = 0; i < inputs.length; i++) {
                if (inputs[i].name == supplierName) {
                    inputs[i].value = data.result;
                    break;
                }
            }
        });
    }
}
/**
 * 输入原供应商编码，查询原供应商名称
 * 
 * @param {}
 *            field
 */
function invalidCodeValueChange(field) {
    supplierCodeValueChange(field, "invalidName");
}

function setButtonDisabled(disabled) {
    document.getElementById("ok_button").disabled = disabled;
}

function writeToForm() {
    var supplierNameNodes = $("invalidName");

    addOrDelRepeat("失效供应商名称", supplierNameNodes.length);

    for (var i = 0; i < supplierNameNodes.length; i++) {
        setUpFieldValue2(getUpFieldsByFieldval("pk_corp").eq(i), $('corpSelect')[i].value);
        setUpFieldValue2(getUpFieldsByFieldval("制造部").eq(i), $("corpSelect")[i].options[$("corpSelect")[i].options.selectedIndex].text);
        for (var key in inputMap) {
            setUpFieldValue2(getUpFieldsByFieldval(key).eq(i), $(inputMap[key])[i].value);
        }
    }
    fy_dialog_close();
}

/**
 * 将填写的内容写入到表单
 */
function okButtonClick() {
    setButtonDisabled(true);
    var supplierNameNodes = $("invalidCode");
    for (var i = 0; i < supplierNameNodes.length; i++) {
        for (var key in notAllowBlank) {
            if ($(key)[i].value == "") {
                alert(notAllowBlank[key] + "不能为空");
                return setButtonDisabled(false);
            } else {
                for (var j = i; j < supplierNameNodes.length; j++) {
                    if (i != j
                            && $("invalidCode")[i].value == $("invalidCode")[j].value) {
                        alert("存在多行相同的失效供应商");
                        return setButtonDisabled(false);
                    }
                }
            }
        }
    }
    writeToForm();
}

function _ajax(url, operator) {
    document.getElementById("lodingDiv").style.height = window.parent.document.body.clientHeight + "px";
    document.getElementById("lodingDiv").style.display = '';
    var xmlhttp = null;
    if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera,
        xmlhttp = new XMLHttpRequest();
    } else {// code for IE6, IE5
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlhttp.onreadystatechange = function () {
        if (xmlhttp.readyState == 4) {
            if (xmlhttp.status == 200) {
                text = xmlhttp.responseText;
                if (text == 1) {
                    alert("失效供应商编码不能为空");
                } else if (text == 2) {
                    alert("用户还未登陆，或者已掉线");
                } else if (text == 3) {
                    alert("制造部ID不能为空。");
                } else if (text == 4) {
                    alert("常数不能为空");
                } else if (text == 4) {
                    alert("目标供应商名称不能为空");
                } else {
                    var data = eval("(" + text + ")");
                    if (data.success)
                        operator(data);
                    else
                        alert(data.result);
                }
            } else {
                alert("连接服务器异常");
            }
            document.getElementById("lodingDiv").style.display = 'none';
            setButtonDisabled(false);
        }
    };
    xmlhttp.open("get", url + "&temp=" + Math.random(), true);
    xmlhttp.send();
}

window.onload = function () {

    /**
     * 界面初始化
     */
    /**
     * 填写新建表单
     */
    // 重复表初始化
    var firstTR = getParentTR(document.getElementById("repeatTable").getElementsByTagName("TR")[0]);
    var repeatOperator = new RepeateTableOperator(firstTR.parentNode);
    repeatOperator.addListeners(firstTR);

    repeatOperator.setAfterAddTrOperate(function () {
        for (var i = 1; i < $('corpSelect').length; i++) {
            $('corpSelect')[i].value = $('corpSelect')[0].value;
        }
    });

    // 制造部下拉列表选择项设置
    var oaAccountID = getUpFieldValue(getUpFieldsByFieldval('单位选择器').eq(0)).id;

    for (var key in corpMap) {
        if (corpMap[key] && corpMap[key] == oaAccountID) {
            $('corpSelect')[0].options
                    .add(createOption(corpMap1[key][1], key));

            if (oaAccountID == "5686590792835548528") {
                $('corpSelect')[0].options.add(createOption("福州福耀模具科技有限公司",
                        "key_1027"));
            }

            break;
        }
    }
    $('corpSelect')[0].options.selectedIndex = 0;

    var pk_corpValue = getUpFieldValue(getUpFieldsByFieldval("pk_corp").eq(0)).value;

    if (oaAccountID == "5686590792835548528") {
        if (pk_corpValue != "") {
            $('corpSelect')[0].value = pk_corpValue;
        }
    }

    // 把表单的内容复制到填写界面的对应的输入框
    var supplierNames = getUpFieldsByFieldval("失效供应商编码");
    repeatOperator.addEmptyTR(firstTR, supplierNames.length - 1);
    for (var i = 0; i < supplierNames.length; i++) {
        $('corpSelect')[i].value = getUpFieldValue(getUpFieldsByFieldval("pk_corp").eq(0)).value;
        for (var key in inputMap) {
            $(inputMap[key])[i].value = getUpFieldValue(getUpFieldsByFieldval(key).eq(i)).value;
        }
    }
};
